import wepy from 'wepy';
import Tips from './Tips';

export default class http {


    static async get(gateway,apiPath, data, loading = true)
    {
        let apiRs=await this.apiRequest('GET', gateway,apiPath,data,"application/json", loading);
        return this.bizExect(apiRs,apiPath)
    }


    static async postForm(gateway,apiPath, data,loading = true) {

        let apiRs=await this.apiRequest('POST', gateway,apiPath, data,"application/x-www-form-urlencoded", loading);
        return this.bizExect(apiRs,apiPath);
    }

    static async postJson(gateway,apiPath, data,loading = true) {
        let apiRs=await this.apiRequest('POST', gateway,apiPath, data,"application/json", loading);
        return this.bizExect(apiRs,apiPath);
    }

    static async postFile(gateway,apiPath, filePath,formData) {

      let apiRs=await this.apiFileRequest(gateway,apiPath, filePath,formData);
      return this.bizExect(apiRs,apiPath);
    }

    static async apiFileRequest(gateway,apiPath, filePath,formData)
    {
        if(wepy.$instance.globalData.stopReq)
        {
            return {
                HttpCode:423,
                Next:true,
                Code:423,
                Msg:"正在登录中，放弃当前请求！",
                Data:null
            };
        }
        let url=this.getApiUrl(gateway,apiPath);
        return await this.wxFileUpload(url, filePath,formData);
    }

    static async wxFileUpload(url, filePath,formData) {

      if(!formData){
        formData={};
      }
      const wpRes=await wepy.uploadFile({
        header:{
         "Req-Host": wepy.$instance.globalData.extConfig.appId,
          "Xkd-From": "weapp",
          "Authorization": 'Bearer ' + wepy.$instance.globalData.jwtToken,
         },
        url: url,
        formData:formData,
        filePath: filePath,
        name: 'wxafile'
      })

      let res =JSON.parse(wpRes.data);

      if(res)
      {
          res.HttpCode=wpRes.statusCode;
          res.Next=true;
      }
      else
      {
          res={
              HttpCode:wpRes.statusCode,
              Code:wpRes.statusCode,
              Data:null,
              Next:true
          };
      };
      return res;
  }



    static bizExect(apiRs,apiPath)
    {

        apiRs.ApiPath=apiPath;
        if(apiRs.domainerror)
        {
            apiRs.Next=false;
            Tips.error("请求域名配置错误");
            return apiRs;
        }

        if(apiRs.HttpCode==423)
        {
            apiRs.Next=false;
            return apiRs;
        }

        if(apiRs.HttpCode==403)
        {
            apiRs.Next=false;

           const returnUrl=this.getCurrentPageUrlWithArgs();///获取返回的PageUrl及参数
           wepy.redirectTo({url:"/pages/home/login?returnUrl="+escape(returnUrl)});
            return apiRs;
        }
        
        return apiRs
    }

    static getCurrentPageUrlWithArgs() {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        let url = "/"+currentPage.route;
        const options = currentPage.options;
        let urlWithArgs = "";
        for (let key in options) {
          const value = options[key];
          urlWithArgs += `${key}=${value}&`;
        }
        if(urlWithArgs!=""){
            urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
            url=`${url}?${urlWithArgs}`;
        }
        return url
      }




    static async apiRequest(method, gateway,apiPath, data,contenType, loading = true)
    {
        if(wepy.$instance.globalData.stopReq)
        {
            return {
                HttpCode:423,
                Next:true,
                Code:423,
                Msg:"正在登录中，放弃当前请求！",
                Data:null
            };
        }


        let url=this.getApiUrl(gateway,apiPath);
        return await this.wxRequest(method, url, data, contenType,loading);
    }




    static getApiUrl(gateway,apiPath)
    {
        let baseUrl = wepy.$instance.globalData.xkdApiDomians;
        let storeId=wepy.$instance.globalData.extConfig.storeId;

       if(baseUrl[gateway]){
           return `${baseUrl[gateway]}/${storeId}/${apiPath}`;
       }
       return baseUrl.default+apiPath;
    }

    static async wxRequest(method, url, data,contenType, loading = true) {
        const param = {
            url: url,
            method: method,
            data: data,
            header: this.GetWxaHeader(contenType)
        };
        if (loading) {
            // Tips.loading();
        }


        const wpRes = await wepy.request(param).catch(ex=>{
           if(ex&&ex.errMsg=="request:fail url not in domain list")
           {
             return {
                statusCode:500,
                domainerror:true
             }
           }
           else
           {
             throw(ex);
           }
         
        });

        let res = wpRes.data;
        if(res)
        {
            res.HttpCode=wpRes.statusCode;
            res.Next=true;
        }
        else
        {
            res={
                HttpCode:wpRes.statusCode,
                Code:wpRes.statusCode,
                Data:null,
                Next:true,
                domainerror:wpRes.domainerror
            };
        };
        return res;
    }

    ///公共请求头
    static GetWxaHeader(contenType) {
        let headerData =
        {
            "Req-Host": wepy.$instance.globalData.extConfig.appId,
            "Content-Type":contenType,//"application/x-www-form-urlencoded"//application/json,
            "Xkd-From": "weapp",
            "Authorization": 'Bearer ' + wepy.$instance.globalData.jwtToken,
        };
        return headerData;
    }

}
